/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-04-20
 * Time:15:53
 */

/**
 * JZ12矩阵中的路径
 */

public class hasPath {
    public boolean hasPath (char[][] matrix, String word) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        boolean[][] visited = new boolean[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (dfs(matrix, word, visited, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] matrix, String word, boolean[][] visited, int row, int col, int index) {
        if (index == word.length()) {
            return true;
        }
        if (row < 0 || row >= matrix.length || col < 0 || col >= matrix[0].length
                || visited[row][col] || matrix[row][col] != word.charAt(index)) {
            return false;
        }
        visited[row][col] = true;
        boolean res = dfs(matrix, word, visited, row - 1, col, index + 1) ||
                dfs(matrix, word, visited, row + 1, col, index + 1) ||
                dfs(matrix, word, visited, row, col - 1, index + 1) ||
                dfs(matrix, word, visited, row, col + 1, index + 1);
        visited[row][col] = false;
        return res;
    }
}
